using ASP;
using ClassLibrary.BusinessLayer.Facade;
using IPMS.AccessAuth;
using IPMS.BLL;
using Resources;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Globalization;
using System.Threading;
using System.Web.Profile;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web;

public partial class Clients : Page, IRequiresSessionState
{
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        //this.clearText();
       // this.setTextReadOnly(true);
       // this.setButtons(string.Empty);
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "Clients");
        if (!canDelete.CanDelete())
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mNoDelete.ToString();
        }
        else
        {
            try
            {
                this.ODSClient.DeleteMethod = "Delete";
                this.ODSClient.DeleteParameters["Original_Client"].DefaultValue = this.txtClient.Text;
                this.ODSClient.Delete();
                this.clearText();
                this.Search();
                this.setTextReadOnly(true);
                this.setButtons(string.Empty);
            }
            catch (Exception ex)
            {
                List<string> lstValues = new List<string>();
                //this.lblError.Text = IPDataFormat.GenerateMessage(ex, lstValues);
                this.lblError.Text = ex.Message.ToString();
                this.chkForOperation.Checked = true;
            }
        }
    }

    protected void btnModify_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "Clients");
        if (!canDelete.CanUpdate())
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mNoEdit.ToString();
        }
        else
        {
            this.setTextReadOnly(false);
            this.setButtons("modify");
            this.txtClient.ReadOnly = true;
            this.txtName.Focus();
        }
    }

    protected void btnNew_Click(object sender, EventArgs e)
    {
        Auth canDelete = new Auth(this.Session["UserId"].ToString(), string.Empty, "Clients");
        if (!canDelete.CanAdd())
        {
            this.lblError.Visible = true;
            this.lblError.Text = Messages.mNoAdd.ToString();
        }
        else
        {
            this.setTextReadOnly(false);
            this.clearText();
            this.setButtons("new");
            this.txtClient.ReadOnly = false;
            this.txtClient.Focus();
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (this.cbForUpdate.Checked)
            {
                this.ODSClient.UpdateMethod = "Update";
                this.ODSClient.UpdateParameters["Name"].DefaultValue = this.txtName.Text;
                this.ODSClient.UpdateParameters["ChineseName"].DefaultValue = this.txtChiName.Text;
                this.ODSClient.UpdateParameters["Address"].DefaultValue = this.txtAddress.Text;
                this.ODSClient.UpdateParameters["ContactPerson"].DefaultValue = this.txtContactPerson.Text;
                this.ODSClient.UpdateParameters["JobTitle"].DefaultValue = this.txtJobTitle.Text;
                this.ODSClient.UpdateParameters["Phone"].DefaultValue = this.txtPhone.Text;
                this.ODSClient.UpdateParameters["Fax"].DefaultValue = this.txtFax.Text;
                this.ODSClient.UpdateParameters["Phone2"].DefaultValue = this.txtPhone2.Text;
                this.ODSClient.UpdateParameters["WebSite"].DefaultValue = this.txtWebSite.Text;
                this.ODSClient.UpdateParameters["ContactPerson2"].DefaultValue = this.txtContactPerson2.Text;
                this.ODSClient.UpdateParameters["Fax2"].DefaultValue = this.txtFax2.Text;
                this.ODSClient.UpdateParameters["EmailAddress"].DefaultValue = this.txtEmailAddress.Text;
                this.ODSClient.UpdateParameters["EmailAddress2"].DefaultValue = this.txtEmailAddress2.Text;
                this.ODSClient.UpdateParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSClient.UpdateParameters["Original_Client"].DefaultValue = this.txtClient.Text;
                this.ODSClient.Update();
            }
            else
            {
                this.ODSClient.InsertMethod = "Insert";
                this.ODSClient.InsertParameters["Client"].DefaultValue = this.txtClient.Text;
                this.ODSClient.InsertParameters["Name"].DefaultValue = this.txtName.Text;
                this.ODSClient.InsertParameters["ChineseName"].DefaultValue = this.txtChiName.Text.ToString();
                this.ODSClient.InsertParameters["Address"].DefaultValue = this.txtAddress.Text;
                this.ODSClient.InsertParameters["ContactPerson"].DefaultValue = this.txtContactPerson.Text;
                this.ODSClient.InsertParameters["JobTitle"].DefaultValue = this.txtJobTitle.Text;
                this.ODSClient.InsertParameters["Phone"].DefaultValue = this.txtPhone.Text;
                this.ODSClient.InsertParameters["Fax"].DefaultValue = this.txtFax.Text;
                this.ODSClient.InsertParameters["Phone2"].DefaultValue = this.txtPhone2.Text;
                this.ODSClient.InsertParameters["WebSite"].DefaultValue = this.txtWebSite.Text;
                this.ODSClient.InsertParameters["ContactPerson2"].DefaultValue = this.txtContactPerson2.Text;
                this.ODSClient.InsertParameters["Fax2"].DefaultValue = this.txtFax2.Text;
                this.ODSClient.InsertParameters["EmailAddress"].DefaultValue = this.txtEmailAddress.Text;
                this.ODSClient.InsertParameters["EmailAddress2"].DefaultValue = this.txtEmailAddress2.Text;
                this.ODSClient.InsertParameters["CreateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSClient.InsertParameters["UpdateBy"].DefaultValue = this.Page.User.Identity.Name.ToString();
                this.ODSClient.InsertParameters["OwnerGroupID"].DefaultValue = this.Session["OwnerGroupID"].ToString();
                this.ODSClient.Insert();
            }
            this.setTextReadOnly(true);
            this.setButtons("save");
            this.cbForUpdate.Checked = false;
            this.clearText();
            this.Search();
        }
        catch (Exception ex)
        {
            List<string> lstValues = new List<string>();
            //this.lblError.Text = IPDataFormat.GenerateMessage(ex, lstValues);
            this.lblError.Text = ex.Message.ToString();
            this.chkForOperation.Checked = true;
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        this.Search();
    }

    protected void clearText()
    {
        this.txtClient.Text = string.Empty;
        this.txtName.Text = string.Empty;
        this.txtChiName.Text = string.Empty;
        this.txtContactPerson.Text = string.Empty;
        this.txtAddress.Text = string.Empty;
        this.txtJobTitle.Text = string.Empty;
        this.txtPhone.Text = string.Empty;
        this.txtFax.Text = string.Empty;
        this.txtPhone2.Text = string.Empty;
        this.txtContactPerson2.Text = string.Empty;
        this.txtFax2.Text = string.Empty;
        this.txtWebSite.Text = string.Empty;
        this.txtEmailAddress.Text = string.Empty;
        this.txtEmailAddress2.Text = string.Empty;
        this.cbForUpdate.Checked = false;
        this.chkForOperation.Checked = false;
        this.lblError.Text = "";
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        this.GridView1.PageIndex = e.NewPageIndex;
        this.GridView1.DataBind();
        this.Search();
    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            this.chkForOperation.Checked = true;
            this.cbForUpdate.Checked = true;
            Client runMethod = new Client(this.GridView1.DataKeys[this.GridView1.SelectedIndex].Values["Client"].ToString());
            runMethod.GetClientDetails();
            this.txtClient.Text = this.GridView1.DataKeys[this.GridView1.SelectedIndex].Values["Client"].ToString();
            this.txtName.Text = runMethod.Client_Name;
            this.txtChiName.Text = runMethod.Client_ChineseName;
            this.txtContactPerson.Text = runMethod.Client_ContactPerson;
            this.txtAddress.Text = runMethod.Client_Address;
            this.txtJobTitle.Text = runMethod.Client_JobTitle;
            this.txtPhone.Text = runMethod.Client_Phone;
            this.txtFax.Text = runMethod.Client_Fax;
            this.txtPhone2.Text = runMethod.Client_Phone2;
            this.txtContactPerson2.Text = runMethod.Client_ContactPerson2;
            this.txtFax2.Text = runMethod.Client_Fax2;
            this.txtWebSite.Text = runMethod.Client_WebSite;
            this.txtEmailAddress.Text = runMethod.Client_EmailAddress;
            this.txtEmailAddress2.Text = runMethod.Client_EmailAddress2;
        }
        catch (NullReferenceException)
        {
        }
        this.setButtons(string.Empty);
    }

    protected override void InitializeCulture()
    {
        string sCulture = ConfigurationManager.AppSettings["DefaultCulture"].ToString();
        try
        {
            sCulture = this.Session["Culture"].ToString();
        }
        catch (NullReferenceException)
        {
        }
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(sCulture);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(sCulture);
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Auth canView = new Auth(this.Session["UserId"].ToString(), string.Empty, "Clients");
        if (!canView.CanView())
        {
            base.Response.Redirect("ErrorPage/NotAllowed.aspx");
        }
        else
        {
            if (!this.chkForOperation.Checked)
            {
                this.setButtons(string.Empty);
                this.setTextReadOnly(true);
            }
            if (!this.Page.IsPostBack)
            {
                ((Label)this.Master.FindControl("lblMstTitle")).Text = " | " + ISitemap.Settings + " | " + ISitemap.MaintenanceFiles + " | " + ISitemap.ClientsList.ToString();

                this.btnDelete.Attributes.Add("onClick", "return confirm('" + Messages.DeleteConfirmation.ToString() + "')");
            }
        }

        if (Convert.ToBoolean(Session["SuperUser"]))
        {
            //GridView1.Columns[GridView1.Columns.Count - 1].Visible = true;
            GridView1.Columns[GridView1.Columns.Count - 2].Visible = true;
        }
        else
        {
            //GridView1.Columns[GridView1.Columns.Count - 1].Visible = false;
            GridView1.Columns[GridView1.Columns.Count - 2].Visible = false;
        }
    }

    protected void Search()
    {
        ClientsFacade facade = new ClientsFacade();
        SqlParameter[] sqlparam = new SqlParameter[5];
        sqlparam[0] = new SqlParameter();
        sqlparam[0].ParameterName = "@Client";
        sqlparam[0].Value = this.txtSearchClient.Text.ToString();
        sqlparam[1] = new SqlParameter();
        sqlparam[1].ParameterName = "@Name";
        sqlparam[1].Value = this.txtSearchName.Text.ToString();
        sqlparam[2] = new SqlParameter();
        sqlparam[2].ParameterName = "@ChineseName";
        sqlparam[2].Value = this.txtSearchChineseName.Text.ToString();
        sqlparam[3] = new SqlParameter();
        sqlparam[3].ParameterName = "@ContactPerson";
        sqlparam[3].Value = this.txtSearchContactPerson.Text.ToString();
        sqlparam[4] = new SqlParameter();
        sqlparam[4].ParameterName = "@superuser ";
        sqlparam[4].Value = (Session["SuperUser"] != null) ? Convert.ToBoolean(Session["SuperUser"]) : false;
        DbParameter[] param = sqlparam;
        DataView dv = facade.GetsClients("_IPMS_ClientSearch_SP", param).DefaultView;
        this.GridView1.DataSourceID = string.Empty;
        this.GridView1.DataSource = dv;
        this.GridView1.DataBind();
    }

    protected void setButtons(string action)
    {
        switch (action)
        {
            case "new":
                this.btnNew.Enabled = false;
                this.btnModify.Enabled = false;
                this.btnSave.Enabled = true;
                this.btnDelete.Enabled = false;
                this.chkForOperation.Checked = true;
                return;

            case "modify":
                this.btnNew.Enabled = false;
                this.btnModify.Enabled = false;
                this.btnSave.Enabled = true;
                this.btnDelete.Enabled = false;
                this.chkForOperation.Checked = true;
                return;

            case "save":
                this.btnNew.Enabled = true;
                this.btnModify.Enabled = false;
                this.btnSave.Enabled = false;
                this.btnDelete.Enabled = false;
                return;
        }
        this.btnNew.Enabled = true;
        this.btnModify.Enabled = this.txtClient.Text.Length != 0;
        this.btnSave.Enabled = false;
        this.btnDelete.Enabled = this.txtClient.Text.Length != 0;
    }

    protected void setTextReadOnly(bool bBool)
    {
        this.txtClient.ReadOnly = bBool;
        this.txtName.ReadOnly = bBool;
        this.txtChiName.ReadOnly = bBool;
        this.txtContactPerson.ReadOnly = bBool;
        this.txtAddress.ReadOnly = bBool;
        this.txtJobTitle.ReadOnly = bBool;
        this.txtPhone.ReadOnly = bBool;
        this.txtFax.ReadOnly = bBool;
        this.txtPhone2.ReadOnly = bBool;
        this.txtContactPerson2.ReadOnly = bBool;
        this.txtFax2.ReadOnly = bBool;
        this.txtWebSite.ReadOnly = bBool;
        this.txtEmailAddress.ReadOnly = bBool;
        this.txtEmailAddress2.ReadOnly = bBool;
    }
    protected void btnNewClients_Click(object sender, EventArgs e)
    {
        Response.Redirect("ClientsAdd.aspx");
    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Restore")
        {
            GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
            int index = row.RowIndex;

            string _client = this.GridView1.DataKeys[index].Values["Client"].ToString().Trim();
            string isDelete = this.GridView1.DataKeys[index].Values["IsDelete"].ToString().Trim();

            if (this.Session["SuperUser"] != null)
            {
                if (Convert.ToBoolean(isDelete) && Convert.ToBoolean(this.Session["SuperUser"]))
                {
                    Client clientBll = new Client(_client);

                    string updateBy = this.Page.User.Identity.Name.ToString();
                    string updateIP = HttpContext.Current.Request.UserHostAddress;

                    bool isSuccess = clientBll.Update(false, updateBy, updateIP, _client);

                    if (isSuccess)
                    {
                        this.GridView1.DataBind();
                    }
                }
            }
        }
    }

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblIsDelete = (Label)e.Row.FindControl("lblIsDelete");
            LinkButton lbtnRestore = (LinkButton)e.Row.FindControl("lbtnRestore");
            Label lblDeleted = (Label)e.Row.FindControl("lblDeleted");
            Label lblNormal = (Label)e.Row.FindControl("lblNormal");

            if (lblIsDelete != null && lbtnRestore != null && lblDeleted != null && lblNormal != null)
            {
                if (Convert.ToBoolean(lblIsDelete.Text))
                {
                    lbtnRestore.Visible = true;
                    lblDeleted.Visible = true;
                    lblNormal.Visible = false;
                }
                else
                {
                    lbtnRestore.Visible = false;
                    lblDeleted.Visible = false;
                    lblNormal.Visible = true;
                }
            }
        }
    }
}
